package com.mzj.saas.jobs.pwd.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.jobs.commons.SqlUtils;
import com.mzj.saas.jobs.pwd.vo.MatchUserLockAuthorVo;

/**
 * 临时密码每月重置使用次数
 * @author shun
 * @createDate: 2022年7月3日 下午3:30:50
 * @version: 1.0
 *
 */
@Service
public class TempPwdService {
	private static Logger log = LoggerFactory.getLogger(TempPwdService.class);

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public String work() throws Exception {
		log.info("临时密码每月重置使用次数 start");
		// 查询生效日期是不当前月份的数据
		SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
		String sql = "SELECT ula.* FROM m_match_user_lock_author ula WHERE ula.effective_july_date not in(?)";
		List<MatchUserLockAuthorVo> list = jdbcTemplate.query(sql,
				new BeanPropertyRowMapper<>(MatchUserLockAuthorVo.class), format.format(new Date()));
		
		if(list.isEmpty()){
			log.info("临时密码每月重置使用次数, 无数据");
			return "SUCCESS";
		}
		// 重置使用次数为0，修改生效日期为当前月份
		List<Object> args = new ArrayList<>();
		args.add(new Date());
		args.add(format.format(new Date()));
		
		List<Long> ids = list.stream().map(tt -> tt.getId()).collect(Collectors.toList());
		ids.forEach(dd ->{
			args.add(dd);
		});
		
		String updateSql = "UPDATE m_match_user_lock_author SET use_number = 0, last_update_time = ?, effective_july_date =? WHERE id IN " + SqlUtils.foreachIn(ids.size());
		log.info("ids={}", JSON.toJSONString(args));
		jdbcTemplate.update(updateSql, args.toArray());
		log.info("临时密码每月重置使用次数 end");
		return "SUCCESS";
	}
}
